<?php
/**
 * Extractors Update Screen
 * 
 * @author Xavier VILAIN
 * @package Orx\Etl
 * @license #license-orx#
 * 
 */
use Fox\Html\Button;
use Orx\Etl\Extractor\Source;
use Fox\Generator;
use Orx\Etl;
use Orx\Etl\Extractor;
use Fox\Html\Screen;

$xview = Xview::instance();
$extractorid = $xview->val('extractor',false);
try {
	$extractor = new Extractor($extractorid);
	$data = $extractor->getData();
	/* @var $source Orx\Etl\Extractor\Source */
	$source = $extractor->source();
	$items = array();
	$data = array_merge($data,$source->parse($data['params']));
	foreach($extractor->items() as $item) {
		$data['mapping'][] = $item->getData();
		$items[$item->position] = $item;
	}
} catch (Fox\Object\Exception\NotExist $e) {
	var_dump($e);
	//$xview->accessDenied();
} 


$screen = new Screen('sExtractor','update');
$screen->pageTitle(Msg(Etl::BUNDLE,Etl::EXTRACTOR_UPDATE_TITLE));
$screen->toolbar()->add(new Button('back',Generator::url('extractors')));
$block = $xview->component('extractors','header');
$screen->add($block);
// Data Source Params
$blParams = $xview->component('extractors','datasource',array('source' => $data['source']));
$screen->add($blParams);
// Items
$blMapping = $xview->module(Generator::url('extractors','mapping',null,array('extractor' => $extractorid)));
$screen->add($blMapping);
$screen->initialize($data);
if($screen->submitted()) {
	$fields = $screen->get();
	if(!$screen->errors()) {
		try {
			// Parse Extractor Data Source Information
			$source = Fox\Dao::load(Source::className(),$fields['source']);
			$fields['params'] = $source->format($fields);
			$extractor->setFields($fields);
			// Handle Extractor Items
			foreach($fields['mapping'] as $itemData) {
				$position = $itemData['position'];
				unset($itemData['conversion_rule']);
				if(isset($items[$position])) {
					$items[$position]->setFields($itemData);
					$extractor->replaceItems($items[$position]);
					unset($items[$position]);
				} else {
					// its a new Item
					$item = new Extractor\Item();
					$item->setFields($itemData);
					$extractor->addToItems($item);
				}
			}
			// Remove Deleted Items
			foreach($items as $itemToDelete) {
				$extractor->deleteFromItems($itemToDelete);
			}
			$extractor->prepareUpdate(Extractor::CHANGE_DEFAULT);
			if($extractor->update()) {
				Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_UPDATE,$extractor->label()));
				$screen->redirect(Generator::url('extractors','update',null,array('extractor' => $extractor->getId())));
			}
		}
		catch (\Fox\Object\Exception\Save $e) {
			Fox\Message::Error($e);
		}
		catch (\Fox\Object\Exception\NotExist $e) {
			Fox\Message::Error($e);
		}
	}
}
echo $screen->render();